package com.sqbang.dbcompare.aop;

import com.sqbang.dbcompare.constant.SystemConstant;
import com.sqbang.dbcompare.pojo.cache.CommonData;
import com.sqbang.dbcompare.pojo.model.BizException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


@Aspect
@Component
public class AuthorityCheckAspect {

    @Pointcut("execution(* com.sqbang.dbcompare.controller..*.*(..)) || @annotation(com.sqbang.dbcompare.aop.AuthorityCheck)")
    public void pointCut() {}

    @Before("pointCut()")
    public void around(JoinPoint point) throws Throwable {

        // 获取注解信息
        MethodSignature signature = (MethodSignature) point.getSignature();

        AuthorityCheck authorityCheck = signature.getMethod().getAnnotation(AuthorityCheck.class);
        if (authorityCheck == null){
            authorityCheck = point.getTarget().getClass().getAnnotation(AuthorityCheck.class);
        }
        if (authorityCheck != null && authorityCheck.flag()) {

            // 校验是否登录
            // 获取session中的用户信息
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            //获取 header 的token 值
            String token = request.getHeader(SystemConstant.AUTH_CODE);
            if (StringUtils.isEmpty(token)) {
                throw new BizException(HttpStatus.NOT_ACCEPTABLE, "没有授权码");
            }
            if (!CommonData.authCode.equals(token)) {
                throw new BizException(HttpStatus.NOT_ACCEPTABLE, "未授权");
            }
        }
    }

}
